home *** CD-ROM | disk | FTP | other *** search
- #define Version 0.2
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <netdb.h>
- #include <stdio.h>
-
- extern int errno;
-
- main(int ac, char *av[])
- {
- /*
- * Strings we send to the client.
- */
-
- char c;
- FILE *fp;
- int fromlen;
- int port;
- char hostname[64];
- char mesg[64][1024];
- char terminat[1024];
- struct hostent *hp;
- register int i, s, ns;
- char pos;
- struct sockaddr_in sin, fsin;
-
- printf("Enter the terminating character: ");
- gets(terminat);
-
-
- pos=0;
-
- printf("\n Enter the initial message: \n");
- do
- {
- pos++;
- gets(mesg[pos]);
- /* printf("%s\n",mesg[pos]);*/
- }
- while (mesg[pos][0]!=terminat[0]);
- printf("Done reading strings...\n");
-
- printf("Converting port number...\n");
- port = atoi(av[1]);
- /*
- * Before we can do anything, we need
- * to know our hostname.
- */
- gethostname(hostname, sizeof(hostname));
-
- /*
- * Now we look up our host to get
- * its network number.
- */
- if ((hp = gethostbyname(hostname)) == NULL) {
- fprintf(stderr, "%s: host unknown.\n", hostname);
- exit(1);
- }
-
-
- /*
- * Get a socket to work with. This socket will
- * be in the Internet domain, and will be a
- * stream socket.
- */
-
-
- printf("Getting a socket...\n");
- if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
- perror("server: socket");
- exit(1);
- }
-
- /*
- * Create the address that we will be binding to.
- * We use port (cmd line) but put it into network
- * byte order. Also, we use bcopy (see
- * Chapter 14) to copy the network number.
- */
- sin.sin_family = AF_INET;
- sin.sin_port = htons(port);
- sin.sin_addr.s_addr = htonl(inet_addr("0.0.0.0"));
-
- /*
- * Try to bind the address to the socket.
- */
-
- printf("Binding...\n");
- if (bind(s, &sin, sizeof(sin)) < 0) {
- perror("server: bind");
- exit(1);
- }
-
- /*
- * Listen on the socket.
- */
- printf("Listening...\n");
- if (listen(s, 5) < 0) {
- perror("server: listen");
- exit(1);
- }
-
- /*
- * Accept connections. When we accept one, ns
- * will be connected to the client. fsin will
- * contain the address of the client.
- */
- starting:
-
- printf("Accepting...\n");
- if ((ns = accept(s, &fsin, &fromlen)) < 0) {
- perror("server: accept");
- exit(1);
- }
-
-
- /*
- * First we send some strings to the client.
- */
- printf("Sending...\n");
- for (i=0; i < pos+1; i++){
- send(ns, mesg[i], strlen(mesg[i]), 0);
- send(ns, "\n",1,0);}
-
- /*
- * We'll use stdio for reading the socket.
- */
- /*
- fp = fdopen(ns, "r");
-
- pos=0;
-
- do
- {
- pos++;
- mesg[pos]=fgetc(fp);
- }
- while (mesg[pos]!='_');
-
- */
-
-
- /*
- * We can simply use close() to terminate the
- * connection, since we're done with both sides.
- */
- printf("Close(ns): %d", close(ns));
- /* printf("Close(s): %d", close(s)); */
-
- goto starting;
- exit(0);
- }
-
-